package threads;

import java.net.DatagramPacket;

import sjtu.ChatClient.HandlerConstants;
import sjtu.ChatClient.SystemConstants;
import sjtu.ChatClient.Util;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.Handler;

public class DecodeImageWorker implements Runnable {
	private Handler handler;
	private DatagramPacket packet;
	
	public DecodeImageWorker(Handler handler, DatagramPacket packet){
		this.handler = handler;
		this.packet = packet;
	}
	
	@Override
	public void run() {
		// TODO Auto-generated method stub
		// read the values of size out, 
		byte [] data = packet.getData();
		int [] sizes = new int[10];
		int i = 0;
		for(i = 0;i < 10;i++){
			sizes[i] = (int) ((data[4 * i + 3] << 24) | (data[4 * i + 2]) << 16 | (data[4 * i + 1] << 8) | (data[4 * i]));
		}
		// find the most frequently appeared value as the correct value of size
		int size = Util.findMostFrequentValue(sizes);
		         
		// decode the rest data as bitmap
		Bitmap bitmap = BitmapFactory.decodeByteArray(data, 40, packet.getLength() - 40);        
		
		// if app running on i9108, rotate the bitmap 90 degrees clockwise
		if(SystemConstants.IS_I9108){
			if(bitmap != null){
				int width = bitmap.getWidth();
				int height = bitmap.getHeight();
				Matrix matrix = new Matrix();
				matrix.postRotate(90);
				Bitmap b = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
				bitmap = b;
			}
		}
		
		handler.obtainMessage(HandlerConstants.IMAGE_DECODED, bitmap).sendToTarget();
	}

}
